<?php

namespace App\Model;

use Hyperf\Database\Model\Relations\BelongsTo;

/**
 * App\PaymentOrder
 *
 * @property int $id
 * @property float $fee 金额
 * @property float $return_fee 退款金额
 * @property string $number 订单号
 * @property \Carbon\Carbon|null $paid_at 支付时间
 * @property string $payment_type 支付方式
 * @property string $out_ord_id 回执单号
 * @property string $payment_id 回执单号
 */
class CardOrder extends Model
{
    public bool $timestamps = true;
    protected ?string $table = 'card_orders';


    const STATUS_UNPAID = 'unpaid';
    const STATUS_PAID = 'paid';
    const STATUS_FAILED = 'failed';
    const STATUS_REFUNDED = 'refunded';


    protected array $fillable = [
        'number', 'fee', 'payment_type','card_no',
        'paid_at', 'out_ord_id', 'status','return_fee','payment_id'
    ];

    protected array $casts = [

    ];

    public function card(): BelongsTo
    {
        return $this->belongsTo(NfcCard::class, 'card_no', 'card_no');
    }


    public function notify($params){
        if ($params['status'] == 'succeeded') {
            $this->status = self::STATUS_PAID;
            $this->paid_at = $params['end_time'];
            $this->payment_id = $params['id'];
            $this->out_ord_id = $params['out_trans_id'];
            $this->save();
            $this->card->amount += $this->fee;
            $this->card->save();
        }else{
            $this->status = self::STATUS_FAILED;
            $this->save();
        }
    }

}
